{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8ce67390",
   "metadata": {},
   "source": [
    "# 前言\n",
    "通过本文，你可以：\n",
    " * 了解AppBuilder Agent MCP Server是什么\n",
    " * 了解如何通过AppBuilder-SDK调用AppBuilder Agent MCP Server\n",
    " * 了解如何通过Cursor调用AppBuilder Agent MCP Server\n",
    "\n",
    "如果你需要了解更多关于AppBuilder结合MCP生态的功能,可跳转到下面的文档：\n",
    "- 主动调用：通过AppBuilder-Agent调用MCP Server\n",
    "  - 代码态调用：[AppBuilder结合端云组件，调用本地MCP Server](./client.ipynb) \n",
    "  - 代码态调用：[AppBuilder结合地图MCP Server，实现智能导航](./baidu_map.ipynb)\n",
    "  - 零代码态调用：[AppBuilder控制台使用MCP](https://cloud.baidu.com/doc/AppBuilder/s/Nm9vmpb3g)\n",
    "- 被动调用：AppBuilder能力，融入MCP生态，可作为MCP Server提供能力\n",
    "  - 组件能力：[AppBuilder组件转MCP Server](./server.ipynb)\n",
    "  - 智能体能力：[AppBuilder Agent MCP Server](./app_mcp_server.ipynb)\n",
    "  - AI搜索能力: [AppBuilder AI搜索MCP Server](https://github.com/baidubce/app-builder/tree/master/python/mcp_server/ai_search)\n",
    "  - RAG能力：[AppBuilder知识库MCP Server](https://github.com/baidubce/app-builder/tree/master/python/mcp_server/knowledge_base)\n",
    "\n",
    "\n",
    "## AppBuilder Agent MCP Server简介\n",
    "千帆AppBuilder提供了关于AppBuilder应用的MCP Server，用户可通过MCP协议调用在AppBuilder平台创建并发布的自定义智能体应用。\n",
    "\n",
    "当前支持获取应用列表、应用对话两大功能。本文讲述如何使用不同客户端调用此服务。\n",
    "\n",
    "对于入门用户，还提供了环境配置、千帆Agent创建等操作步骤。已熟悉用户可以直接跳过环境配置、应用创建部分。\n",
    "\n",
    "## 安装配置步骤\n",
    "\n",
    "### 配置基础环境\n",
    "\n",
    "#### 1、安装Python\n",
    "\n",
    "大部分的MCP Server，例如Unity和Blender，都是Python SDK\n",
    "安装Python最简单的方法是安装Miniconda\n",
    "**注意：请确保安装的python>=3.12**\n",
    "\n",
    "[Miniconda官网](https://www.anaconda.com/docs/getting-started/miniconda/install)\n",
    "\n",
    "#### 2、下载Appbuilder-SDK\n",
    "\n",
    "为了实现Appbuilder-SDK对AppBuilder Agent MCP Server的代码态调用，需要在conda环境下载appbuilder-sdk包\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96a39a88",
   "metadata": {
    "vscode": {
     "languageId": "shellscript"
    }
   },
   "outputs": [],
   "source": [
    "!python3 -m pip install httpx appbuilder-sdk mcp"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e7d417d",
   "metadata": {},
   "source": [
    "\n",
    "## 创建百度智能云千帆AppBuilder智能体\n",
    "\n",
    "首先创建一个千帆AppBuilder智能体。\n",
    "\n",
    "### 1、进入百度智能云千帆AppBuilder主页\n",
    "\n",
    "进入百度智能云千帆AppBuilder主页，免费试用\n",
    "\n",
    "- [百度智能云千帆AppBuilder主页](https://qianfan.cloud.baidu.com/appbuilder)\n",
    "\n",
    "### 2、创建【自主规划Agent】\n",
    "\n",
    "- [Appbuilder 自主规划Agent概述](https://cloud.baidu.com/doc/AppBuilder/s/km4i50me8)\n",
    "\n",
    "- [快速创建应用](https://cloud.baidu.com/doc/AppBuilder/s/Om0ks82ow)\n",
    "\n",
    "\n",
    "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%88%9B%E5%BB%BA%E8%87%AA%E4%B8%BB%E8%A7%84%E5%88%92Agent.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T15%3A00%3A03Z%2F-1%2Fhost%2F31df73d263dbc1dc7e28a6bc077b37c70ce27af91ac7888ff9151c7ef1d58b04)\n",
    "\n",
    "### 3、输入一句简单的提示词，让AI自动扩写\n",
    "\n",
    "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%88%9B%E5%BB%BA%E8%87%AA%E4%B8%BB%E8%A7%84%E5%88%92agent.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T03%3A23%3A29Z%2F-1%2Fhost%2F67b7a5d0c38c12f79bc925e995c8f09775eb37bfe9025f61a593080c3c05c82c)\n",
    "\n",
    "### 4、删除自动配置的组件\n",
    "\n",
    "因为我们调用MCP工具，所以不需要使用AppBuilder自带组件\n",
    "\n",
    "### 5、配置模型\n",
    "\n",
    "将规划模型和问答模型的思考轮数拉满\n",
    "\n",
    "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E9%85%8D%E7%BD%AE%E6%A8%A1%E5%9E%8B.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T03%3A27%3A44Z%2F-1%2Fhost%2Ffd031f86bf71a0ca7e32db70533a76db9c39757a139f94b34f487eae9f860534)\n",
    "\n",
    "### 6、发布应用\n",
    "\n",
    "发布应用，在【个人空间】中，查看应用ID，记下来\n",
    "\n",
    "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%8F%91%E5%B8%83Agent%E5%BA%94%E7%94%A8.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T03%3A30%3A26Z%2F-1%2Fhost%2Ff66b1bef4bb432ddd59ca07189ed210fb475c6363559dfd0c7ab53ef47a6240f)\n",
    "\n",
    "### 7、创建Appbuilder API key\n",
    "\n",
    "- [Appbuilder API key授权](https://cloud.baidu.com/doc/AppBuilder/s/lm68r8e6i)\n",
    "\n",
    "- [Appbuilder API 控制台管理中心](https://console.bce.baidu.com/iam/#/iam/apikey/list)\n",
    "\n",
    "在【API Key】界面中，创建一个新的Key，并添加刚刚创建的应用，记下来。\n",
    "\n",
    "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%88%9B%E5%BB%BAAPPBUILDER-TOKEN.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T14%3A49%3A27Z%2F-1%2Fhost%2F9266ac8c93a262d2905811877d680f53af26668a0ee09e1b3a61c0b721de253c)\n",
    "\n",
    "同时配置API key权限，将上文创建的应用添加到API key权限中。\n",
    "\n",
    "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E6%B7%BB%E5%8A%A0Agent%E6%9D%83%E9%99%90.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T03%3A33%3A59Z%2F-1%2Fhost%2Feda8af9c241207cf07ff2edb85b2271ce48aade84775ca2273580ad13f03a5dc)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3aa3c0a2",
   "metadata": {},
   "source": [
    "## 使用AppBuilder SDK调用\n",
    "\n",
    "### 1. 获取应用列表\n",
    "查询用户的应用列表。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3e7b9a90",
   "metadata": {},
   "outputs": [],
   "source": [
    "import asyncio\n",
    "import os\n",
    "import json\n",
    "from appbuilder.mcp_server.client import MCPClient\n",
    "\n",
    "os.environ[\"APPBUILDER_TOKEN\"] = \"YOUR_APPBUILDER_TOKEN\"\n",
    "\n",
    "async def main():\n",
    "    client = MCPClient()\n",
    "    await client.connect_to_server(service_url=service_url)\n",
    "    result = await client.call_tool(\"get_all_apps\", {})\n",
    "    for app_info in result.content:\n",
    "        app_info = json.loads(app_info.text)\n",
    "        print(app_info[\"id\"] + \"\\t\" + app_info[\"name\"])\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    service_url = \"http://appbuilder.baidu.com/v2/app/mcp/sse?api_key=\" + os.environ.get(\"APPBUILDER_TOKEN\")\n",
    "\n",
    "    loop = asyncio.get_event_loop()\n",
    "    loop.run_until_complete(main())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60df365f",
   "metadata": {},
   "source": [
    "控制台会打印你的应用ID、应用名，参考如下：\n",
    "\n",
    "```bash\n",
    "909*****-***a-****-****-*********2c93    我的Agent应用\n",
    "697*****-***9-****-****-*********360b    我的Agent应用\n",
    "963*****-***2-****-****-*********21d1    我的Agent应用\n",
    "34f*****-***b-****-****-*********3df2    我的Agent应用\n",
    "773*****-***8-****-****-*********62df    图像识别示例\n",
    "```\n",
    "\n",
    "### 2. 进行Agent对话\n",
    "使用MCP协议跟Agent进行对话。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50c87488",
   "metadata": {},
   "outputs": [],
   "source": [
    "import asyncio\n",
    "import json\n",
    "import os\n",
    "from appbuilder.mcp_server.client import MCPClient\n",
    "\n",
    "os.environ[\"APPBUILDER_TOKEN\"] = \"YOUR_APPBUILDER_TOKEN\"\n",
    "os.environ[\"APP_ID\"] = \"YOUR_APP_ID\"\n",
    "\n",
    "\n",
    "async def main():\n",
    "    client = MCPClient()\n",
    "    await client.connect_to_server(service_url=service_url)\n",
    "    app_id = os.environ.get(\"APP_ID\")\n",
    "    result = await client.call_tool(\"create_conversation\", {\"app_id\": app_id})\n",
    "    conversation_id = result.content[0].text\n",
    "    query = \"你能做什么？\"\n",
    "    result = await client.call_tool(\n",
    "        \"run\",\n",
    "        {\n",
    "            \"app_id\": app_id,\n",
    "            \"conversation_id\": conversation_id,\n",
    "            \"query\": query,\n",
    "        },\n",
    "    )\n",
    "    print(result.content[0].text)\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    service_url = (\n",
    "        \"http://appbuilder.baidu.com/v2/app/mcp/sse?api_key=\"\n",
    "        + os.environ.get(\"APPBUILDER_TOKEN\")\n",
    "    )\n",
    "\n",
    "    loop = asyncio.get_event_loop()\n",
    "    loop.run_until_complete(main())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df473bce",
   "metadata": {},
   "source": [
    "控制台会打印对话的返回。参考如下：\n",
    "```bash\n",
    "作为植物识别专家，我专门负责识别和鉴定各种植物种类。我可以通过使用植物识别组件来分析植物的特征，如叶子形状、花朵颜色、果实形态等，从而准确确定植物的种类。无论你是对路边的野花好奇，还是对家中盆栽的种类有疑问，我都可以帮助你进行识别和解答。\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b68c4d6",
   "metadata": {},
   "source": [
    "## 使用Cursor调用\n",
    "### Cursor配置\n",
    "api_key=上面步骤获取到的api key，格式为\"bce-v3/ALTAK...\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b292ee1",
   "metadata": {
    "vscode": {
     "languageId": "json"
    }
   },
   "outputs": [],
   "source": [
    "{\n",
    "    \"mcpServers\": {\n",
    "        \"appbuilder-app\": {\n",
    "            \"url\": \"http://appbuilder.baidu.com/v2/app/mcp/sse?api_key=bce-v3/ALTAK...\"\n",
    "        }\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "804d655d",
   "metadata": {},
   "source": [
    "配置后，在Cursor设置页面可看到`get_all_apps`、`create_converstation`、`run`三个Tool。\n",
    "![cursor config](./image/cursor_agent_mcp_config.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "338eb0cb",
   "metadata": {},
   "source": [
    "### 获取应用列表\n",
    "![get_app_apps](./image/cursor_agent_get_all_apps.png)\n",
    "\n",
    "### 应用对话\n",
    "![cursor agent chat](./image/cursor_agent_run.png)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
